<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="add_role_dialog = true">添加角色</el-button>
      <el-table :data="tableData" :border="true" stripe style="width: 100%">
        <el-table-column type="expand">
          <!-- eslint-disable-next-line-->
          <template slot-scope="props">
            <el-row :class="['bootom', index1 == 0 ? 'top' : '', 'disflex']"
              v-for="(item1, index1) in props.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag @close="removtag3(props.row, item1.id)" closable type="primary" disable-transitions>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级 -->
              <el-col :span="19">
                <el-row :class="[index2 == 0 ? '' : 'top', 'disflex']" v-for="(item2, index2) in item1.children"
                  :key="item2.id">
                  <el-col :span="6">
                    <el-tag @close="removtag3(props.row, item2.id)" closable type="success" disable-transitions>
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag @close="removtag3(props.row, item3.id)" closable v-for="(item3) in item2.children"
                      :key="item3.id" type="warning" disable-transitions>
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="set_role_btn(scope.row.id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="delete_role_btn(scope.row.id)" size="mini" type="danger" icon="el-icon-delete">删除
            </el-button>
            <el-tooltip :enterable="false" class="item" effect="dark" content="分配权限" placement="top">
              <el-button @click="allot_role_btn(scope.row)" size="mini" type="warning" icon="el-icon-setting">权限分配
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加角色" @close="add_role_close" :visible.sync="add_role_dialog" width="50%">
      <el-form label-width="80px" ref="add_role_from_ref" :model="add_role_from" :rules="add_role_rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="add_role_from.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="add_role_from.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="add_role_dialog = false">取 消</el-button>
        <el-button type="primary" @click="add_role_ok">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" @close="set_role_close" :visible.sync="set_role_dialog" width="50%">
      <el-form label-width="80px" ref="set_role_from_ref" :model="set_role_from" :rules="add_role_rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="set_role_from.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="set_role_from.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="set_role_dialog = false">取 消</el-button>
        <el-button type="primary" @click="set_role_ok()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="编辑角色" @close="allot_role_close" :visible.sync="allot_role_dialog" width="50%">
      <el-tree ref="tree" :data="allot_role_data" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="efaultCheckedKeys" :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allot_role_dialog = false">取 消</el-button>
        <el-button type="primary" @click="allot_role_ok()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      //数据
      tableData: [],
      /*
        添加角色
      */
      add_role_dialog: false,
      add_role_from: {
        roleName: '',
        roleDesc: ''
      },
      add_role_rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ]
      },
      /*
        编辑角色
      */
      set_role_dialog: false,
      set_role_from: {
        roleName: '',
        roleDesc: ''
      },
      set_role_rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ]
      },

      /*
        分配权限
      */
      allot_role_dialog: false,
      allot_role_data: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      efaultCheckedKeys: [],
      allot_role_roleId: '',
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    //页面数据
    async getlist() {
      let { data: res } = await this.$http.get(`roles`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.tableData = res.data;

      // console.log(this.tableData);
    },

    /*
    添加角色
    */

    //确定按钮
    add_role_ok() {
      this.$refs.add_role_from_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        let { data: res } = await this.$http.post(`roles`, this.add_role_from);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.getlist();
        this.add_role_dialog = false
      })

    },
    //弹框消失事件
    add_role_close() {
      this.$refs.add_role_from_ref.resetFields();
    },

    /*
      编辑角色
    */

    //编辑按钮
    async set_role_btn(id) {
      let { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.set_role_from = res.data
      this.set_role_dialog = true;
    },
    //弹框消失事件
    set_role_close() {
      this.$refs.set_role_from_ref.resetFields();
    },
    //弹框确定
    async set_role_ok() {
      this.$refs.set_role_from_ref.validate(async v => {
        if (!v) return this.$message.error('表单校验错误');
        this.set_role_from.id = this.set_role_from.roleId;
        let { data: res } = await this.$http.put(`roles/${this.set_role_from.roleId}`, this.set_role_from);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.getlist();
        this.set_role_dialog = false;
      })
    },

    /*
      删除按钮
    */
    //删除一个数据
    delete_role_btn(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //删除操作
        let { data: res } = await this.$http.delete(`roles/${id}`);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.getlist();
        this.$message.success('删除成功');
      }).catch(() => { });
    },

    /*
      分配权限
    */
    //分配按钮
    async allot_role_btn(role) {
      this.allot_role_roleId = role.id
      let { data: res } = await this.$http.get(`rights/tree`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.allot_role_data = res.data;
      this.foreachCheckedKeys(role)
      this.allot_role_dialog = true
    },

    //遍历三级菜单 打钩的
    foreachCheckedKeys(node) {
      if (!node.children) {
        return this.efaultCheckedKeys.push(node.id)
      }
      node.children.forEach(item => {
        this.foreachCheckedKeys(item)
      });
    },

    //弹框关闭事件
    allot_role_close() {
      this.efaultCheckedKeys = []
    },

    //弹框确定按钮
    async allot_role_ok() {
      let key = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()];
      let str = key.join(',')
      let { data: res } = await this.$http.post(`roles/${this.allot_role_roleId}/rights`, { rids: str });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getlist()
      this.allot_role_dialog = false;
    },

    /*
      其他
    */
    removtag3(role, rightid) {
      // console.log(role, rightid);
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success('删除成功');
        //role.children是当前数据下的所有权限
        //res返回的就是最新当前角色最新数据  所以直接覆盖数据就行
        role.children = res.data
      }).catch(() => { });
    }
  },
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}

.bootom {
  border-bottom: 1px solid #eee;
}

.top {
  border-top: 1px solid #eee;
}

.disflex {
  display: flex;
  align-items: center;
}
</style>